package com.bookstore.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.bookstore.entity.po.AuthorPo;
import com.bookstore.entity.pojo.R;
import com.bookstore.service.AuthorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("author")
public class AuthorController {
    @Autowired
    AuthorService authorService;

    @GetMapping("getByPage")
    public R getByPage(Integer start,Integer offset){
        List<AuthorPo> list = authorService.list();
        if(start + offset < list.size())
         return R.success(list.subList(start,offset + start)) ;
        else
          return R.success(list.subList(start,list.size()));
    }
    @GetMapping("getAll")
    public R getAll(){
        List<AuthorPo> list = authorService.list();
        return R.success(list);
    }
    @PostMapping("save")
    public R save (@RequestBody AuthorPo authorPo){
        AuthorPo authorPo1 = new AuthorPo();
        authorPo1.setName(authorPo.getName());
        return authorService.save(authorPo1)?R.success():R.error();
    }
    @PostMapping("update")
    public R update(@RequestBody AuthorPo authorPo){
        return authorService.update(authorPo,new QueryWrapper<AuthorPo>().eq("id",authorPo.getId()))?R.success():R.error();
    }
    @GetMapping("count")
    public R count (){
        return R.success(authorService.count());
    }

    @GetMapping("findByName")
    public R findByName(String name) {
        QueryWrapper<AuthorPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name);
        List<AuthorPo> list = authorService.list(queryWrapper);
        return R.success(list);
    }
}
